<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>兑换码管理</title>
  <style>
    .el-dialog {
      padding: 0 20px;
    }

    .add-btn {
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding: 10px;
    }

    .content-header {
      position: relative;
      padding: 15px 15px 0 15px;
    }

    .content-header>h1 {
      margin: 0;
      font-size: 24px;
      font-weight: normal;
    }

    .content-header>h1>small {
      font-size: 15px;
      display: inline-block;
      padding-left: 4px;
      font-weight: 300;
    }

    .content-header>.breadcrumb {
      float: right;
      background: transparent;
      margin-top: 0;
      margin-bottom: 0;
      font-size: 12px;
      padding: 7px 5px;
      position: absolute;
      top: 20px;
      right: 10px;
      border-radius: 2px;
    }

    .app-container {
      background: #fff;
      margin: 15px 30px 15px 15px;
    }

    .box {
      position: relative;
      border-radius: 3px;
      background: #ffffff;
      border-top: 3px solid #3c8dbc;
      padding: 10px;
      margin-bottom: 20px;
      width: 100%;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    }

    .filter-container {
      padding: 10px 0 15px 0;
    }

    .filter-container .el-button,
    .filter-container .el-input__inner {
      padding: 0 15px;
      height: 34px;
      line-height: 34px;
    }
  </style>
  <link rel="stylesheet" href="../plugins/elementui/index.css">
  <script src="../js/vue.js"></script>
  <script src="../plugins/elementui/index.js"></script>
  <script src="../js/axios-0.18.0.js"></script>
</head>

<body>
  <div id="app">
    <div class="content-header">
      <h1>网站管理<small>兑换码管理</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>网站管理</el-breadcrumb-item>
        <el-breadcrumb-item>兑换码管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="app-container">
      <div class="box">

        <div class="filter-container">
          <el-select v-model="pagination.status" placeholder="请选择状态" style="width: 150px;" class="filter-item">
            <el-option label="全部" value=""></el-option>
            <el-option label="未兑换" value="NotRedeemed"></el-option>
            <el-option label="已兑换" value="AlreadyRedeemed"></el-option>
          </el-select>
          <el-input placeholder="兑换码" v-model="pagination.redeemCode" style="width: 200px;"
            class="filter-item"></el-input>
          <el-input placeholder="id" v-model="pagination.id" style="width: 200px;"
            class="filter-item"></el-input>
          <el-button @click="findSearchPage()" class="dalfBut">查询</el-button>
        </div>
        <div class="add-btn">
          <el-button type="primary" size="small" @click="beginAdd">新增兑换码</el-button>
          <el-button type="success" size="small" @click="exportRedeemCodes">导出兑换码</el-button>
          <el-pagination v-show="total > pageSize" @current-change="query" :current-page="lastPage"
            style="margin-top: 5px" background :page-size="pageSize" :page-sizes="pageSizes"
            @size-change="handleSizeChange" layout="prev, pager, next, total, sizes" :total="total">
          </el-pagination>
        </div>
        <el-table :data="redeemCodes" border size="small" current-row-key="id" stripe highlight-current-row>
          <el-table-column prop="id" label="ID" width="120" align="center"></el-table-column>
          <el-table-column prop="redeemCode" label="兑换码" align="center"></el-table-column>
          <el-table-column prop="userRole" label="用户角色" align="center">
            <template slot-scope="scope">
              <span>{{ getUserRoleText(scope.row.userRole) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <span>{{ getStatusText(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="validity" label="有效期(天)" align="center">
            <template slot-scope="scope">
              <span>{{ convertMinutesToDays(scope.row.validity) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="兑换用户" align="center"></el-table-column>
          <el-table-column align="center" label="操作" fixed="right" :width="160">
            <template slot-scope="scope">
              <!--              <el-button type="primary" plain icon="el-icon-edit" circle size="mini"-->
              <!--                @click="handleEdit(scope.$index, scope.row)"></el-button>-->
              <el-button type="danger" plain icon="el-icon-delete" circle size="mini"
                @click="handleDelete(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog title="兑换码信息" :visible.sync="formVisible" width="50%" style="padding: 0 20px;">
          <el-form :model="redeemCode" size="small" label-position="left" :label-width="formLabelWidth"
            :loading="loading">
            <el-form-item label="用户角色">
              <el-select style="width: 200px;" v-model="redeemCode.userRole" placeholder="请选择用户角色">
                <el-option label="普通会员" :value="1"></el-option>
                <el-option label="高级会员" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量">
              <el-input style="width: 200px;" v-model="redeemCode.num" type="number" placeholder="请输入数量"></el-input>
            </el-form-item>
            <el-form-item label="激活时间">
              <el-select style="width: 200px;" v-model="redeemCode.validity" placeholder="请选择激活时间">
                <el-option label="1天" :value="1440"></el-option>
                <el-option label="3天" :value="4320"></el-option>
                <el-option label="7天" :value="10080"></el-option>
                <el-option label="30天" :value="43200"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="formVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdate" :loading="loading">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>

  <script>
    axios.interceptors.request.use(
      config => {
        return config
      },
      error => {
        console.log(error)
        Promise.reject(error)
      }
    )

    const app = new Vue({
      el: "#app",
      data: {
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          redeemCode: '',
          status: '',
          id: ''
        },
        pageSize: 5,
        pageSizes: [5, 10, 20, 50, 100, 200],
        redeemCodes: [],
        total: 1000,
        formVisible: false,
        formLabelWidth: "100px",
        redeemCode: {
          id: null,
          redeemCode: '',
          userRole: 1,
          status: '',
          validity: 1,
          userName: '',
          num: 1
        },
        isEdit: false,
        lastPage: 1,
        loading: false,
      },
      created() {
        this.query(1);
      },
      watch: {
        pageSize() {
          this.query(1);
        }
      },
      methods: {
        findSearchPage() {
          this.lastPage = 1;
          this.query();
        },
        handleSizeChange(s) {
          this.pageSize = s;
        },
        beginAdd() {
          this.isEdit = false;
          this.redeemCode = {
            userRole: 1,
            status: 'NotRedeemed',
            validity: 1440,
            num: 1
          };
          this.formVisible = true;
        },
        async query(page) {
          this.lastPage = page;
          const res = await axios.get("/redeemCode/page", {
            params: {
              pageNo: this.lastPage ? this.lastPage : 1,
              pageSize: this.pageSize,
              redeemCode: this.pagination.redeemCode,
              status: this.pagination.status,
              id: this.pagination.id
            }
          })
          this.redeemCodes = res.data.records
          this.total = res.data.total
        },
        handleEdit(v1, v2) {
          if (v2.status !== 'NotRedeemed') {
            this.$message({
              message: '只能编辑未兑换的兑换码！',
              type: 'warning'
            });
            return;
          }
          this.isEdit = true;
          this.redeemCode = {
            id: v2.id,
            userRole: v2.userRole,
            validity: v2.validity
          };
          this.formVisible = true;
        },
        handleDelete(v1, v2) {
          this.$confirm('此操作将永久删除兑换码信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteById(v2.id);
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },
        async saveOrUpdate() {
          this.loading = true;
          const data = new FormData();
          if (this.isEdit) {
            // 编辑操作
            data.append('id', this.redeemCode.id);
          }
          // 新增和编辑都需要的字段
          data.append('userRole', this.redeemCode.userRole);
          data.append('validity', this.redeemCode.validity);
          data.append('num', this.redeemCode.num);

          const url = this.isEdit ? "/redeemCode/update" : "/redeemCode/add";
          try {
            const res = await axios.post(url, data);
            const { code, msg } = res.data;
            if (code !== 200) {
              this.$message({
                message: msg,
                type: 'error'
              });
              return;
            }
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.formVisible = false;
            this.query(1);
          } catch (error) {
            console.log(error)
            this.$message({
              message: '请求失败'+error,
              type: 'error'
            });
          } finally {
            this.loading = false;
          }
        },
        async deleteById(id) {
          const res = await axios.get("/redeemCode/delete", { params: { id: id } })
          const { code, msg } = res.data
          if (code !== 200) {
            this.$message({
              message: msg,
              type: 'error'
            });
            return
          }
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.query(this.lastPage)
        },
        getUserRoleText(role) {
          switch (role) {
            case 1:
              return '普通会员';
            case 2:
              return '高级会员';
            default:
              return '未知角色';
          }
        },
        getStatusText(status) {
          switch (status) {
            case 'NotRedeemed':
              return '未兑换';
            case 'AlreadyRedeemed':
              return '已兑换';
            default:
              return '未知状态';
          }
        },
        convertMinutesToDays(minutes) {
          return minutes / 1440 + '天';
        },
        async exportRedeemCodes() {
          try {
            const response = await axios.get('/redeemCode/export', { responseType: 'blob' });
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'redeem_codes.txt');
            document.body.appendChild(link);
            link.click();
          } catch (error) {
            this.$message({
              message: '导出失败',
              type: 'error'
            });
          }
        },
      }
    })
  </script>
</body>

</html>